package edu.ayit.service.impl;

import edu.ayit.dao.TypeRepository;
import edu.ayit.pojo.Type;
import edu.ayit.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    @Override
    public Type getType(Long id) {
        return typeRepository.getOne(id);
    }

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    //分页
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Transactional
    //更新
    @Override
    public Type updateType(Long id, Type type) {
        Type type2 = typeRepository.getOne(id);
        if(type2 == null){
            throw new RuntimeException("不存在该分类!");
        }
        BeanUtils.copyProperties(type,type2);//将type的值赋给type2,因为type2中有id
        return typeRepository.save(type2);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }

    @Override
    public Type getTypeByName(String name) {
        Type type = typeRepository.findTypeByName(name);
        return type;
    }

    @Override
    public List<Type> getList() {
        return typeRepository.findAll();
    }

    @Override
    public List<Type> getListTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }
}
